<?php 
/*
  Oauth2.0 验证辅助程序

*/


if (!defined('WEBSITE'))
{
	class oauth2 extends cls_http
	{
		public $tokenURL;
		public $authorizeURL;
		public $scope = '';
		public $app_key;
		public $app_secret;
		public $display = '';
		public $token = array();
		
		function getauthorizeURL( $callblock , $spal = array())
		{
			$pare = array();
			$pare['client_id'] = $this->app_key;
			$pare['redirect_uri'] = $callblock;
			$pare['response_type'] = 'code';
			$pare['state'] = $callblock;
			$pare['scope'] = $this->scope;
			$pare['display'] = $this->display;
			
			$pare = $this->unset_null($pare);
			
			$p = array_merge( $pare , $spal );
			
			return $this->authorizeURL .'?'. http_build_query($p);
		}
		
		function getToken( $met = 'POST' ,  $spal = array())  // 参数可有可无  方便兼容  //  返回JSON 数据
		{
			if(!empty($_REQUEST['error']))
			{
				$this->error('获取Token失败' , $msg);
				return false;
			}
			
			$pare = array();
			$pare['client_id'] = $this->app_key;
			$pare['client_secret'] = $this->app_secret;
			$pare['grant_type'] = 'authorization_code';
			$pare['code'] = $_REQUEST['code'];
			$pare['redirect_uri'] = $_REQUEST['state'];
			
			$pare = $this->unset_null($pare);
			
			$p = array_merge( $pare , $spal );
			
			$result = $this->http($this->tokenURL , $met , $p);
			
			$token = json_decode($result , true);
			
			if(!empty($token['error']))
			{
				$this->error('get Token failed' , $token);
				return false;
			}
			$this->token = $token;
			return $token; 
		}
		
		function setToken($token)
		{
			$this->token = $token;
		}
		
		function getOauthMsg($url , $met = 'POST' , $spal = array() , $isrefToken = false)
		{
			$pare = array(
				'client_id' => $this->app_key,
				'client_secret' => $this->app_secret,
				'access_token' => $this->token['access_token'],
			);
			if( $isrefToken && !empty($this->token['refresh_token']))
			{
				$pare['refresh_token'] = $this->token['refresh_token'];
			}
			
			$p = array_merge( $pare , $spal );
			
			$result = $this->http($url , $met  , $p);
			
			$info = json_decode($result , true);
			
			return $info;
		}
		function error($str , $msg){ } // 虚函数
		function unset_null( $pare )
		{
			$arr = $pare;
			foreach($arr as $key => $val)
			{
				if(empty($val))
				{
					unset($arr[$key]);
				}
			} 
			return $arr;
		}
	}
}
?>